package com.example.dessert.controller.fore;

import com.example.dessert.controller.BaseController;
import com.example.dessert.entity.User;
import com.example.dessert.service.IRedisService;
import com.example.dessert.service.UserService;
import com.example.dessert.util.ResponsePojo;
import com.example.dessert.util.ResultCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @ClassName: LoginController
 * @Description: 登录
 * @Author li
 * @Date 2021/12/28
 * @Version 1.0
 */
@Controller
@RequestMapping("/fore")
public class LoginController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private IRedisService iRedisService;

    /**
     * 登录
     */
    @GetMapping("/login")
    public String login() {
        return "fore/login";
    }

    /**
     * 注册校验
     */
    @PostMapping("/doLogin")
    @ResponseBody
    public ResponsePojo doLogin(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        logger.info("User login request parameters :{}", map);

        String account = (String)map.get("account");
        User user = userService.accountQueryUser(account);
        logger.info("Account query user results :{}", user);

        if (user == null) {
            return ResponsePojo.error(ResultCode.EXP_INVALID_ACCOUNT,"用户不存在，请确认登录账号！");
        }
        String password = (String)map.get("password");
        if(!StringUtils.equals(password,user.getPassword())){
            return ResponsePojo.error(ResultCode.EXP_INVALID_ACCOUNT,"登录密码错误！");
        }

        HttpSession session = request.getSession();
        session.setAttribute("userId", user.getId());

        return ResponsePojo.ok();

    }

}
